﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using UnityEditor.ProjectWindowCallback;
using UnityEditor;

public static class CreateExtension {
	[MenuItem("Assets/Create/My C# Scripts",false,79)]
	public static void CreateMyCS()
	{
		ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
                    ScriptableObject.CreateInstance<CreateAssetAction>(),
                    GetSelectedPath() + "/NewBehaviourScript.cs",
                    null,
                    Application.dataPath+"/Extension/79-C# Script-NewBehaviourScript.cs.txt");
	}

	static string GetSelectedPath(){
		string selectedPath = "Assets";

		Object[] selection = Selection.GetFiltered(typeof(Object),SelectionMode.Assets);

		foreach (Object obj in selection) {
			selectedPath = AssetDatabase.GetAssetPath(obj);
			if (!string.IsNullOrEmpty(selectedPath) && File.Exists(selectedPath)) {
				selectedPath = Path.GetDirectoryName(selectedPath);
				break;
			}
		}
		return selectedPath;
	}
}

public class CreateAssetAction : EndNameEditAction{
	public override void Action (int instanceId, string pathName, string resourceFile)
	{
		Object obj = CreateAssetFromTemplate(pathName, resourceFile);
		ProjectWindowUtil.ShowCreatedAsset(obj);
	}

	internal static Object CreateAssetFromTemplate(string pathName, string resourceFile){
		string fullPath = Path.GetFullPath(pathName);
		StreamReader sr = new StreamReader(resourceFile);
		string content = sr.ReadToEnd();
		sr.Close();

		string fileName = Path.GetFileNameWithoutExtension(pathName);
		content = content.Replace("#TITLE#",fileName)
						 .Replace("#NAME#",fileName)
						 .Replace("#AUTHOR#","姚鑫")
						 .Replace("#DATE#",System.DateTime.Now.ToString());
		StreamWriter sw = new StreamWriter(fullPath,false,Encoding.UTF8);
		sw.Write(content);
		sw.Close();

		AssetDatabase.ImportAsset(fullPath);
		AssetDatabase.Refresh();
		return AssetDatabase.LoadAssetAtPath(pathName,typeof(Object));
	}
}
